package cap.dao.impl;


import cap.bean.BlogInfo;
import cap.dao.BlogInfoDao;
import cap.db.DBPool;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class BlogInfoDaoImpl implements BlogInfoDao {
	Connection conn=null;
	PreparedStatement ps=null;
	ResultSet rs=null;
	/**
	 *添加博客
	 */
	@Override
	public int insertBlogInfo(int userId, String blogName, String description, String annoucement) {
		int res = -1;
		try {
			String sql="insert into blog_info values(NULL, ?, ?, ?, ?)";
			conn=DBPool.getConn();
			ps=conn.prepareStatement(sql);
			ps.setInt(1,userId);
			ps.setString(2,blogName);
			ps.setString(3,description);
			ps.setString(4,annoucement);
			res=ps.executeUpdate();
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			DBPool.close(rs,ps,conn);
		}
		return res;
	}

	/**
	 *根据用户id获取博客
	 */
	@Override
	public BlogInfo getByuserId(int userId) {
		BlogInfo bi = null;
		try {
			String sql="select * from blog_info where user_id=?";
			conn=DBPool.getConn();
			ps=conn.prepareStatement(sql);
			ps.setInt(1,userId);
			rs=ps.executeQuery();
			if (rs.next()) {
				bi = new BlogInfo();
				bi.setId(rs.getInt("id"));
				bi.setUserId(rs.getInt("user_id"));
				bi.setBlogName(rs.getString("blog_name"));
				bi.setDescription(rs.getString("description"));
				bi.setPropagate(rs.getString("propagate"));
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			DBPool.close(rs,ps,conn);
		}

		return bi;
	}
	/**
	 *修改博客信息
	 */
	@Override
	public int updateBlogInfo(int userId, String blogName, String description, String propagate) {
		int res = -1;
		try {
			String sql="update blog_info " +
					"set blog_name=?, description=?, propagate=? where user_id=?";
			conn=DBPool.getConn();
			ps=conn.prepareStatement(sql);
			ps.setString(1,blogName);
			ps.setString(2,description);
			ps.setString(3,propagate);
			ps.setInt(4,userId);
			res=ps.executeUpdate();
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			DBPool.close(rs,ps,conn);
		}

		return res;
	}
}
